# -*- coding: utf-8 -*-

from PyQt5.QtWidgets import QMainWindow, QApplication, QMessageBox, QGraphicsScene, QGraphicsPixmapItem, QHeaderView, \
    QTableWidgetItem
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtCore import pyqtSlot, QDateTime, QTimer
from Ui_MainWindow import Ui_MainWindow
from DaMai.Cookies import Cookie
from DaMai.Autoticket import Concert
from os.path import exists
from os import remove
import webbrowser
import json
import sys


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        self.start_flag = False
        self._loop_flag_ = False
        self._target_sec_ = 0
        self._timer_ = QTimer()
        QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.set_default_value()

    def set_default_value(self):
        default_value = '''{"sess": [3, 1, 2], 
        "price": [1, 3], "date": 0, 
        "real_name": "", "nick_name": "\u9ea6\u5b501lRkR", 
        "contact"： "李耳", "contact_phone": "13166981277",
        "ticket_num": 1, "damai_url": "https://www.damai.cn/", 
        "target_url": "\u8bf7\u8f93\u5165\u76ee\u6807\u8d2d\u7968\u7f51\u5740",
        "loop": 1, "is_e_ticket": 1,
        "browser": 0}'''
        if not exists("config.json"):
            with open("./config.json", "w+", encoding='utf-8') as f:
                f.write(default_value)
        try:
            with open('./config.json', 'r', encoding='utf-8') as f:
                config = json.loads(f.read())
            self.sess_edit.setText(','.join(str(s) for s in config['sess']))
            self.ticket_class_edit.setText(','.join(str(s) for s in config['price']))
            self.data_order_box.setCurrentText(str(config['date']))
            if config['real_name']:
                self.real_name_box.setChecked(True)
                self.real_name_edit.setText(",".join(str(s) for s in config['real_name']))
            else:
                self.real_name_box.setChecked(False)
                self.real_name_edit.setText("")
            #self.nick_name_edit.setText(config['nick_name'])
            self.ticket_num_edit.setText(str(config['ticket_num']))
            self.target_url_edit.setText(config['target_url'])
            self.tableWidget.setItem(0, 0, QTableWidgetItem(config['nick_name']))
            self.tableWidget.setItem(0, 1, QTableWidgetItem(config['user_phone']))
            self.tableWidget.setItem(0, 2, QTableWidgetItem(config['passwd']))
            self.tableWidget.setItem(0, 3, QTableWidgetItem(config['contact']))
            self.tableWidget.setItem(0, 4, QTableWidgetItem(config['contact_phone']))
            if int(config['loop']) == 1:
                self.loop_box.setChecked(True)
            else:
                self.loop_box.setChecked(False)
            # params: 场次优先级，票价优先级，日期， 实名者序号, 用户昵称， 购买票数， 官网网址， 目标网址， 浏览器
        except Exception as e:
            print(e)
            raise Exception("***错误：初始化失败，请检查配置文件***")
        self.ticket_time.setDateTime(QDateTime.currentDateTime())

        self._timer_.timeout.connect(self.on_timer_timeout)

    # TODO: add qr code to ui
    '''
    def set_pic(self, a):
        print(a)
        pic = QPixmap("qr.png")
        item = QGraphicsPixmapItem(pic)
        scene = QGraphicsScene()
        scene.addItem(item)
        self.graphicsView.setScene(scene)
    '''

    def check_value(self):
        '''麦子0kwbm'''
        real_name_list = []
        sess_list = []
        price_list = []
        real_name_list = []
        nick_name = ''
        contact = ''
        contact_phone = ''
        user_phone = ''
        passwd = ''
        ticket_num = 0
        target_url = ''
        date = 0
        is_e_ticket = True
        e_flag = False
        sess = self.sess_edit.text()
        sess_list = sess.split(',')
        try:
            sess_list = list(map(int, sess_list))
        except ValueError:
            QMessageBox.warning(self, "⚠️", "场次优先级格式错误或未填写！")
            e_flag = True
            sess_list = []
        print(sess_list)

        price = self.ticket_class_edit.text()
        price_list = price.split(',')
        try:
            price_list = list(map(int, price_list))
        except ValueError:
            QMessageBox.warning(self, "⚠️", "票价优先级格式错误或者未填写！")
            e_flag = True
            price_list = []
        print(price_list)

        date = self.data_order_box.currentText()
        date = int(date)
        print(date)

        real_name = ''
        if self.real_name_box.isChecked():
            real_name = self.real_name_edit.text()
            if real_name:
                real_name_list = real_name.split(',')
                try:
                    real_name_list = list(map(int, real_name_list))
                except ValueError:
                    QMessageBox.warning(self, "⚠️", "实名序号格式错误或者未填写！")
                    e_flag = True
                    real_name_list = []
                print(real_name_list)
        else:
            real_name_list = []

        try:
            nick_name = self.tableWidget.item(0, 0).text()
            print(nick_name)
        except AttributeError:
            QMessageBox.warning(self, "⚠️", "用户名用于验证是否登陆成功，必须填写！")
            e_flag = True
        try:
            user_phone = self.tableWidget.item(0, 1).text()
        except AttributeError:
            pass
        try:
            passwd = self.tableWidget.item(0, 2).text()
            print(passwd)
        except AttributeError:
            pass
        try:
            contact = self.tableWidget.item(0, 3).text()
            print(contact)
        except AttributeError:
            pass
        try:
            contact_phone = self.tableWidget.item(0, 4).text()
            print(contact_phone)
        except AttributeError:
            pass
        ticket_num = self.ticket_num_edit.text()
        try:
            ticket_num = int(ticket_num)
        except ValueError:
            QMessageBox.warning(self, "⚠️", "购买票数填写错误！")
            e_flag = True
            ticket_num = 0
        print(ticket_num)

        target_url = self.target_url_edit.text()
        if target_url.find("detail.damai.cn") == -1 and target_url.find("piao.damai.cn") == -1:
            QMessageBox.warning(self, "警告", "购票网址填写错误！")
            e_flag = True
        print(target_url)

        is_e_ticket = self.e_ticket_box.isChecked()

        if not e_flag:
            try:
                with open('./config.json', 'r', encoding='utf-8') as f:
                    print(user_phone)
                    print(passwd)
                    config = json.loads(f.read())
                    config['sess'] = sess_list
                    config['price'] = price_list
                    config['date'] = date
                    if real_name:
                        config['real_name'] = real_name_list

                    else:
                        config['real_name'] = ''
                    config['nick_name'] = nick_name
                    config['user_phone'] = user_phone
                    config['passwd'] = passwd
                    config['contact'] = contact
                    config['contact_phone'] = contact_phone
                    config['ticket_num'] = ticket_num
                    config['target_url'] = target_url
                    config['is_e_ticket'] = is_e_ticket
            except Exception:
                QMessageBox.critical(self, "❎", "读取配置文件失败，检查有无更新！")
                self.close()

            try:
                with open("./config.json", 'w', encoding='utf-8') as f:
                    f.write(json.dumps(config))
            except Exception:
                QMessageBox.critical(self, "❎", "写入配置文件失败，检查有无更新！")
                self.close()
            # thread = Cookie()
            # thread.sig.connect(self.set_pic)
            # thread.get_cookie()
            # QMessageBox.information(self, "警告", "检查通过，请点击开始")
        else:
            pass

        return e_flag

    @pyqtSlot()
    def on_real_name_box_clicked(self):
        if self.real_name_box.isChecked():
            self.real_name_edit.setEnabled(True)
        else:
            self.real_name_edit.setDisabled(True)

    @pyqtSlot()
    def on_loop_box_clicked(self):
        if self.loop_box.isChecked():
            self._loop_flag_ = True
        else:
            self._loop_flag_ = False

    @pyqtSlot()
    def on_timing_box_clicked(self):
        target_date_time = self.ticket_time.dateTime()
        current_date_time = QDateTime.currentDateTime()
        self._target_sec_ = current_date_time.secsTo(target_date_time)
        self._timer_.start(1000)

    @pyqtSlot()
    def on_timer_timeout(self):
        self._target_sec_ -= 1
        if self._target_sec_ == 0:
            self._timer_.stop()
        else:
            self.lcd_timer.display(self._target_sec_)

    @pyqtSlot()
    def on_help_button_clicked(self):
        webbrowser.open("https://gitee.com/clearpass/DamaiAutoTicket")

    @pyqtSlot()
    def on_login_button_clicked(self):
        if self.check_value():
            QMessageBox.warning(self, "警告️", "配置失败，请检查配置选项！")
        else:
            try:
                with open('./config.json', 'r', encoding='utf-8') as f:
                    config = json.loads(f.read())
            except Exception as e:
                print(e)
                raise Exception("***错误：初始化失败，请检查配置文件***")
        if config:
            browser = Cookie(config['user_phone'], config['passwd'])
            if exists("cookies.pkl"):
                reply = QMessageBox.question(self, '登录', '您已登录，是否更换了账号？',
                                             QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)
                if reply == QMessageBox.Yes:
                    remove('cookies.pkl')
                    browser.get_cookie()
                else:
                    QMessageBox.information(self, "提示", "登录成功，可以开始抢票啦！")
            else:
                browser.get_cookie()
                if exists("cookies.pkl"):
                    QMessageBox.information(self, "提示", "登录成功，可以开始抢票啦！")
                else:
                    QMessageBox.warning(self, "警告", "登录失败，请重新登录")

    @pyqtSlot()
    def on_start_button_clicked(self):
        if self.check_value():
            QMessageBox.warning(self, "警告️", "配置失败，请检查配置选项！")
        else:
            self.start_flag = True
            self.close()
            try:
                with open('./config.json', 'r', encoding='utf-8') as f:
                    config = json.loads(f.read())
                # params: 场次优先级，票价优先级，日期， 实名者序号, 用户昵称， 购买票数， 官网网址， 目标网址， 浏览器
                con = Concert(config['sess'], config['price'], config['date'], config['real_name'], config['nick_name'],
                              config['user_phone'], config['passwd'],
                              config['contact'], config['contact_phone'], config['ticket_num'],
                              config['damai_url'], config['target_url'], config['browser'], config['is_e_ticket'])
            except Exception as e:
                print(e)
                raise Exception("***错误：初始化失败，请检查配置文件***")
            con.enter_concert()
            # while True: # 可用于无限抢票，防止弹窗类异常使抢票终止
            if True:
                try:
                    if con.type == 1:  # detail.damai.cn
                        con.choose_ticket_1()
                        con.check_order_1()
                    elif con.type == 2:  # piao.damai.cn
                        con.choose_ticket_2()
                        con.check_order_2()
                    # break
                except Exception as e:
                    print(e)
                    con.driver.get(con.target_url)
            con.finish()


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    ui = MainWindow()
    icon = QIcon("damai.ico")
    ui.setWindowIcon(icon)
    ui.show()
    sys.exit(app.exec_())